package com.xx.xiawan.videoplayer;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.pili.pldroid.player.AVOptions;
import com.pili.pldroid.player.PLMediaPlayer;
import com.pili.pldroid.player.widget.PLVideoTextureView;
import com.xiaxiang.xiawan.video.VideoInfoListener;
import com.xiaxiang.xiawan.video.XXVideoBase;

/**
 * Created by Administrator on 2017-10-24.
 */

public class XXVideoPlayer extends XXVideoBase implements PLMediaPlayer.OnInfoListener {
   // private int mDisplayAspectRatio = PLVideoTextureView.ASPECT_RATIO_FIT_PARENT; //default
    private int mDisplayAspectRatio = PLVideoTextureView.ASPECT_RATIO_PAVED_PARENT; //default
    private static final int MESSAGE_ID_RECONNECTING = 0x01;
    private static final int MEDIA_CODEC = 1;
    //当前播放的是否为在线直播，如果是，则底层会有一些播放优化
    private static final int IS_LIVE_STREAMING = 0;
    private PLVideoTextureView mVideoView;
    private String mVideoPath = null;
    /**
     * 视频的方向
     */
    private int mVideoRotation;
    private boolean needResume;

    /** 最大声音 */
    private int mMaxVolume;
    /** 当前声音 */
    private int mVolume = -1;
    /** 当前亮度 */
    private float mBrightness = -1f;
    public XXVideoPlayer(Activity act){
        super(act);

    }
    public void setVideoView(Object videoView){
        mVideoView = (PLVideoTextureView)videoView;
       // mVideoView.get
        init();
    }
    private void init(){
        AVOptions options = new AVOptions();

//        int isLiveStreaming = getIntent().getIntExtra("liveStreaming", 1);
        // the unit of timeout is ms
        int isLiveStreaming =IS_LIVE_STREAMING;
        options.setInteger(AVOptions.KEY_PREPARE_TIMEOUT, 4* 1000);
        options.setInteger(AVOptions.KEY_GET_AV_FRAME_TIMEOUT, 4 * 1000);
        // Some optimization with buffering mechanism when be set to 1
        options.setInteger(AVOptions.KEY_LIVE_STREAMING, isLiveStreaming);
        if (isLiveStreaming == 1) {
           // options.setInteger(AVOptions.KEY_DELAY_OPTIMIZATION, 1);
        }

        // 1 -> hw codec enable, 0 -> disable [recommended]
//        int codec = getIntent().getIntExtra("mediaCodec", 0);
        int codec = MEDIA_CODEC;
        options.setInteger(AVOptions.KEY_MEDIACODEC, codec);

        // whether start play automatically after prepared, default value is 1
        options.setInteger(AVOptions.KEY_START_ON_PREPARED, 0);

        mVideoView.setAVOptions(options);
     //   mVideoView.setOnInfoListener(mOnInfoListener);
//        mVideoView.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
        mVideoView.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
        mVideoView.setOnCompletionListener(mOnCompletionListener);
        mVideoView.setOnSeekCompleteListener(mOnSeekCompleteListener);
        mVideoView.setOnErrorListener(mOnErrorListener);
   //     mVideoView.setVideoPath(mVideoPath);
        mVideoView.setDisplayAspectRatio(mDisplayAspectRatio);
        mVideoView.setOnPreparedListener(mOnPreparedListener);
        mVideoView.setOnVideoSizeChangedListener(new PLMediaPlayer.OnVideoSizeChangedListener() {
            @Override
            public void onVideoSizeChanged(PLMediaPlayer plMediaPlayer, int width, int height) {
//                Logger.i("width:" + width + "---heightL:" + height);
                System.out.println("width:" + width + "---heightL:" + height);
                if (width > height&&mVideoRotation==0) {
                    //旋转方向
                    System.out.println("旋转方向");
                    //mAct.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
                //如果视频角度是90度
                if(mVideoRotation==90)
                {
                    //旋转视频
                    System.out.println("旋转方向" + mVideoRotation);
                    mVideoView.setDisplayOrientation(270);
                }


            }
        });
        mVideoView.setOnInfoListener(this);
    }
    private PLMediaPlayer.OnCompletionListener mOnCompletionListener = new PLMediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(PLMediaPlayer plMediaPlayer) {
//            finish();
            if(mVideoInfoListener != null){
                mVideoInfoListener.onCompletion();
            }
            //showToastTips("视频播放完成");
        }
    };

    private PLMediaPlayer.OnBufferingUpdateListener mOnBufferingUpdateListener = new PLMediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(PLMediaPlayer plMediaPlayer, int precent) {
            Log.e("me"," precent is "+precent);
        }
    };

    private PLMediaPlayer.OnSeekCompleteListener mOnSeekCompleteListener = new PLMediaPlayer.OnSeekCompleteListener() {
        @Override
        public void onSeekComplete(PLMediaPlayer plMediaPlayer) {
//            Logger.d("onSeekComplete !");
            System.out.println("onSeekComplete !");
            System.out.println();
        }

    };

    private PLMediaPlayer.OnPreparedListener mOnPreparedListener = new PLMediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(PLMediaPlayer plMediaPlayer) {
            Log.e("me"," onPrepared ");
            if(mVideoInfoListener != null){
                mVideoInfoListener.onPrepared();
            }
        }
    };

    private PLMediaPlayer.OnErrorListener mOnErrorListener = new PLMediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(PLMediaPlayer mp, int errorCode) {
            switch (errorCode) {
                case PLMediaPlayer.ERROR_CODE_INVALID_URI:
                    showToastTips("Invalid URL !");
                    break;
                case PLMediaPlayer.ERROR_CODE_404_NOT_FOUND:
                    showToastTips("404 resource not found !");
                    break;
                case PLMediaPlayer.ERROR_CODE_CONNECTION_REFUSED:
                    showToastTips("Connection refused !");
                    break;
                case PLMediaPlayer.ERROR_CODE_CONNECTION_TIMEOUT:
                    showToastTips("Connection timeout !");
                    break;
                case PLMediaPlayer.ERROR_CODE_EMPTY_PLAYLIST:
                    showToastTips("Empty playlist !");
                    break;
                case PLMediaPlayer.ERROR_CODE_STREAM_DISCONNECTED:
                    showToastTips("Stream disconnected !");
                    break;
                case PLMediaPlayer.ERROR_CODE_IO_ERROR:
                    showToastTips("Network IO Error !");
                    break;
                case PLMediaPlayer.ERROR_CODE_UNAUTHORIZED:
                    showToastTips("Unauthorized Error !");
                    break;
                case PLMediaPlayer.ERROR_CODE_PREPARE_TIMEOUT:
                    showToastTips("Prepare timeout !");
                    break;
                case PLMediaPlayer.ERROR_CODE_READ_FRAME_TIMEOUT:
                    showToastTips("Read frame timeout !");
                    break;
                case PLMediaPlayer.MEDIA_ERROR_UNKNOWN:
                default:
                    showToastTips("unknown error !");
                    break;
            }
            // Todo pls handle the error status here, retry or call finish()
         //   mAct.finish();
            // If you want to retry, do like this:
            // mVideoView.setVideoPath(mVideoPath);
            // mVideoView.start();
            // Return true means the error has been handled
            // If return false, then `onCompletion` will be called
            return true;
        }
    };
    private void showToastTips(final String tips) {
        mAct.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast mToast = Toast.makeText(mAct, tips, Toast.LENGTH_SHORT);
                mToast.show();
            }
        });
    }

    public void pause(){
        mVideoView.pause();
    }

    public int getDisplayAspectRatio(){
        return mVideoView.getDisplayAspectRatio();
    }

    public void stopPlayback(){
        mVideoView.stopPlayback();
    }

    public void setDisplayOrientation(int rotation){
        mVideoView.setDisplayOrientation(rotation);
    }
    public void setVideoPath(String path){
        mVideoPath = path;
        mVideoView.setVideoPath(path);
    }

    public void start(){
        mVideoView.start();
    }
    public void setDisplayAspectRatio(int displayAspectRatio){
        mVideoView.setDisplayAspectRatio(displayAspectRatio);
    }

    public void setOnInfoListener(VideoInfoListener onInfoListener){
        // mVideoView.setOnInfoListener(onInfoListener);
        super.setOnInfoListener(onInfoListener);
    }

    @Override
    public boolean onInfo(PLMediaPlayer plMediaPlayer, int what, int extra) {
        Log.e("me"," onInfo what is "+what);
        switch (what) {
            case PLMediaPlayer.MEDIA_INFO_BUFFERING_START:
                if(mVideoInfoListener != null){
                    mVideoInfoListener.mediaInfoBufferingStart(extra);
                }
                break;
            case PLMediaPlayer.MEDIA_INFO_BUFFERING_END:
                if(mVideoInfoListener != null){
                    mVideoInfoListener.mediaInfoBufferingEnd(extra);
                }
                break;
            case PLMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                if(mVideoInfoListener != null){
                    mVideoInfoListener.mediaInfoRenderingStart(extra);
                }
                break;
            case PLMediaPlayer.MEDIA_INFO_BUFFERING_BYTES_UPDATE:
                if(mVideoInfoListener != null){
                    mVideoInfoListener.mediaInfoBufferingBytesUpdate(extra);
                }
                break;
            case 10001:
                if(mVideoInfoListener != null){
                    mVideoInfoListener.doOther(extra);
                }
                break;
        }
        return false;
    }
}
